<?php 
include_once "include/config.php";
include_once "header.php";
//Cálculo de fechas
$today = date("Y-m-d");
$fecha = date_create($today);
date_add($fecha, date_interval_create_from_date_string('1 days'));
$manana = date_format($fecha, 'Y-m-d');
$fecha = date_create($today);
date_add($fecha, date_interval_create_from_date_string('7 days'));
$semana = date_format($fecha, 'Y-m-d');

//Variables a utilizar
session_start();
$autentificado = $_SESSION["autentificado"];
$ultimoAcceso = $_SESSION["ultimoAcceso"];
$id_user = $_SESSION["id_user"];
$email = $_SESSION["email"];
$task=$_GET['task'];
$periodo=$_GET['periodo'];

//Si se pide logout
if($task == "logout") {
	session_start(); 
	$_SESSION["autentificado"] = "NO";
	session_destroy(); 
	header("Location: index.php");
}
?>

<!DOCTYPE html>
<html>
  <head>
    <!--
    This site was based on the Represent.LA project by:
    - Alex Benzer (@abenzer)
    - Tara Tiger Brown (@tara)
    - Sean Bonner (@seanbonner)
    
    Create a map for your startup community!
    https://github.com/abenzer/represent-map
    -->
	<!-- 
	Ha sido modificado y adaptado por: 
	- dandolamurga (@dandolamurga_) 
	para localizar las Huelgas y Manifestaciones en España
	-->
    <title>Huelgas y Manifiestaciones</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:700|Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link href="./bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="./bootstrap/css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="map.css?nocache=289671982568" type="text/css" />
    <link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="mobile.css" type="text/css" />
    <script src="./scripts/jquery-1.7.1.js" type="text/javascript" charset=utf-8></script>
    <script src="./bootstrap/js/bootstrap.js" type="text/javascript" charset=utf-8></script>
    <script src="./bootstrap/js/bootstrap-typeahead.js" type="text/javascript" charset=utf-8></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="./scripts/label.js"></script>
    
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-38378176-1']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
    <script type="text/javascript">
      var map;
      var infowindow = null;
      var gmarkers = [];
      var markerTitles =[];
      var highestZIndex = 0;  
      var agent = "default";
      var zoomControl = true;
      var periodo = "<?php echo $periodo; ?>" ;
	  var maxLengthDesc = <?php echo $place_desc_maxlength; ?>;

	// Creates associative array (object) of query params
    var queryParameters = (function()
    {
        var result = {};
   
        if (window.location.search){
            // split up the query string and store in an associative array
            var params = window.location.search.slice(1).split("&");
            for (var i = 0; i < params.length; i++){
                var pair = params[i].split("=");
                result[pair[0]] = decodeURIComponent(pair[1]);
            }
        }
        return result;
    }());
    
      // detect browser agent
      $(document).ready(function(){
        if(navigator.userAgent.toLowerCase().indexOf("iphone") > -1 || navigator.userAgent.toLowerCase().indexOf("ipod") > -1) {
          agent = "iphone";
          zoomControl = false;
        }
        if(navigator.userAgent.toLowerCase().indexOf("ipad") > -1) {
          agent = "ipad";
          zoomControl = false;
        }
      }); 
      

      // resize marker list onload/resize
      $(document).ready(function(){
        resizeList() 
      });
      $(window).resize(function() {
        resizeList();
      });
      
      // description area text limit
      /*$(document).ready(function(){
	    $('#textarea_feedback').html('Quedan '+ maxLengthDesc + ' caracteres');
	
	    $('#textarea').keyup(function() {
	        var textLength = $('#textarea').val().length;
	        var textRemaining = maxLengthDesc - textLength;
	
	        $('#textarea_feedback').html('Quedan '+ textRemaining + ' caracteres');
	    });
      });*/
     
      $(document).ready(function(){
      	if(queryParameters["task"] == "modal_add"){
      		$('#modal_add').modal('show');
      	}
      });
      
      // resize marker list to fit window
      function resizeList() {
        newHeight = $('html').height() - $('#topbar').height();
        $('#list').css('height', newHeight + "px"); 
        $('#menu').css('margin-top', $('#topbar').height()); 
      }



	  // set config.php map options
	  var zoomMarker = <?php echo $map_zoom_marker; ?>;
		
      // initialize map
      function initialize() {
        // set map styles
        var mapStyles = [
         {
            featureType: "road",
            elementType: "geometry",
            stylers: [
              { hue: "#8800ff" },
              { lightness: 100 }
            ]
          },{
            featureType: "road",
            stylers: [
              { visibility: "on" },
              { hue: "#91ff00" },
              { saturation: -62 },
              { gamma: 1.98 },
              { lightness: 45 }
            ]
          },{
            featureType: "water",
            stylers: [
              { hue: "#005eff" },
              { gamma: 0.72 },
              { lightness: 42 }
            ]
          },{
            featureType: "transit.line",
            stylers: [
              { visibility: "off" }
            ]
          },{
            featureType: "administrative.locality",
            stylers: [
              { visibility: "on" }
            ]
          },{
            featureType: "administrative.neighborhood",
            elementType: "geometry",
            stylers: [
              { visibility: "simplified" }
            ]
          },{
            featureType: "landscape",
            stylers: [
              { visibility: "on" },
              { gamma: 0.41 },
              { lightness: 46 }
            ]
          },{
            featureType: "administrative.neighborhood",
            elementType: "labels.text",
            stylers: [
              { visibility: "on" },
              { saturation: 33 },
              { lightness: 20 }
            ]
          }
        ];

		
        // set map options
        var myOptions = {
          zoom: 6,
          //minZoom: 10,
          center: new google.maps.LatLng(40.40,-2.48),
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          streetViewControl: false,
          mapTypeControl: false,
          panControl: false,
          zoomControl: zoomControl,
          styles: mapStyles,
          zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL,
            position: google.maps.ControlPosition.LEFT_CENTER
          }
        };
        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
        zoomLevel = map.getZoom();

        // prepare infowindow
        infowindow = new google.maps.InfoWindow({
          content: "holding..."
        });

        // only show marker labels if zoomed in
        google.maps.event.addListener(map, 'zoom_changed', function() {
          zoomLevel = map.getZoom();
          if(zoomLevel <= zoomMarker) {
            $(".marker_label").css("display", "none");
          } else {
            $(".marker_label").css("display", "inline");
          }
        });

        // markers array: name, type (icon), lat, long, description, uri, address
        markers = new Array();
        <?php
          $marker_id = 0;
          foreach($places_types as $type) {
          	switch($periodo) {
					case hoy :
						$places = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND start_date <= DATE('$today') AND end_date >= DATE('$today') ORDER BY title");
						break;
					case manana :
						$places = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND start_date <= DATE('$manana') AND end_date >= DATE('$manana') ORDER BY title");
						break;
					case semana :
						$places = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND start_date <= DATE('$semana') AND end_date >= DATE('$today') ORDER BY title");
						break;
					default :
						$places = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND end_date >= DATE('$today') ORDER BY title");
						
					}
          		            
            $places_total = mysql_num_rows($places);
            while($place = mysql_fetch_assoc($places)) {
              $place[title] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[title])));
              $place[description] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[description])));
              $place[hashtag] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[hashtag])));
              $place[uri] = addslashes(htmlspecialchars($place[uri]));
              $place[address] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[address])));
              $place[start_date] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[start_date])));
              $place[end_date] = htmlspecialchars_decode(addslashes(htmlspecialchars($place[end_date])));
              echo "
                markers.push(['".$place[title]."', '".$place[type]."', '".$place[lat]."', '".$place[lng]."', '".$place[description]."', '".$place[uri]."', '".$place[address]."', '".$place[hashtag]."', '".$place[start_date]."', '".$place[end_date]."']); 
                markerTitles[".$marker_id."] = '".$place[title]."';
              "; 
              $count[$place[type]]++;
              $marker_id++;
            }
          } 
        ?>

        // add markers
        jQuery.each(markers, function(i, val) {
          infowindow = new google.maps.InfoWindow({
            content: ""
          });

          // offset latlong ever so slightly to prevent marker overlap
          rand_x = Math.random();
          rand_y = Math.random();
          val[2] = parseFloat(val[2]) + parseFloat(parseFloat(rand_x) / 6000);
          val[3] = parseFloat(val[3]) + parseFloat(parseFloat(rand_y) / 6000);

          // show smaller marker icons on mobile
          if(agent == "iphone") {
            var iconSize = new google.maps.Size(16,19);
          } else {
            iconSize = null;
          }

          // build this marker
          var markerImage = new google.maps.MarkerImage("./images/icons/"+val[1]+".png", null, null, null, iconSize);
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng(val[2],val[3]),
            map: map,
            title: '',
            clickable: true,
            infoWindowHtml: '',
            zIndex: 10 + i,
            icon: markerImage
          });
          marker.type = val[1];
          gmarkers.push(marker);

          // add marker hover events (if not viewing on mobile)
          if(agent == "default") {
            google.maps.event.addListener(marker, "mouseover", function() {
              this.old_ZIndex = this.getZIndex(); 
              this.setZIndex(9999); 
              $("#marker"+i).css("display", "inline");
              $("#marker"+i).css("z-index", "99999");
            });
            google.maps.event.addListener(marker, "mouseout", function() { 
              if (this.old_ZIndex && zoomLevel <= zoomMarker) {
                this.setZIndex(this.old_ZIndex); 
                $("#marker"+i).css("display", "none");
              }
            }); 
          }

          // format marker URI for display and linking
          var markerURI = val[5];
          if(markerURI.substr(0,7) != "http://") {
            markerURI = "http://" + markerURI; 
          }
          var markerURI_short = markerURI.replace("http://", "");
          var markerURI_short = markerURI_short.replace("www.", "");
          
          //Formato para el hashtag
          var hashtag = val[7].replace('#','');;
          var hashtagURI = "https://twitter.com/intent/tweet?button_hashtag=" + hashtag;
          
          //Formato para las fechas
          var fechas = "Desde el "+val[8]+" al "+val[9];



          // add marker click effects (open infowindow)
          google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(
              "<div class='marker_title'>"+val[0]+"</div>"
              + "<div class='marker_uri'></span><a target='_blank' href='"+markerURI+"'>"+markerURI_short+"</a></span><span style='padding:15px'><a target='_blank' class='twitter-hashtag-button' href='"+hashtagURI+"'>"+val[7]+"</a></span></div>"
              + "<div class='marker_desc'>"+val[4]+"</div>"
              + "<div class='marker_address'>"+val[6]+"</div>"
              + "<div class='marker_address'>Desde el "+val[8]+" al "+val[9]+"</div>"
            );
            infowindow.open(map, this);
          });

            
          // add marker label
          var latLng = new google.maps.LatLng(val[2], val[3]);
          var label = new Label({
            map: map,
            id: i
          });
          label.bindTo('position', marker);
          label.set("text", val[0]);
          label.bindTo('visible', marker);
          label.bindTo('clickable', marker);
          label.bindTo('zIndex', marker);
        });


        // zoom to marker if selected in search typeahead list
        $('#search').typeahead({
          source: markerTitles, 
          onselect: function(obj) {
            marker_id = jQuery.inArray(obj, markerTitles);
            if(marker_id > -1) {
              map.panTo(gmarkers[marker_id].getPosition());
              map.setZoom(zoomMarker);
              google.maps.event.trigger(gmarkers[marker_id], 'click');
            }
            $("#search").val("");
          }
        });
      } 


      // zoom to specific marker
      function goToMarker(marker_id) {
        if(marker_id) {
          map.panTo(gmarkers[marker_id].getPosition());
          map.setZoom(zoomMarker);
          google.maps.event.trigger(gmarkers[marker_id], 'click');
        }
      }

      // toggle (hide/show) markers of a given type (on the map)
      function toggle(type) {
        if($('#filter_'+type).is('.inactive')) {
          show(type); 
        } else {
          hide(type); 
        }
      }

      // hide all markers of a given type
      function hide(type) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].type == type) {
            gmarkers[i].setVisible(false);
          }
        }
        $("#filter_"+type).addClass("inactive");
      }

      // show all markers of a given type
      function show(type) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].type == type) {
            gmarkers[i].setVisible(true);
          }
        }
        $("#filter_"+type).removeClass("inactive");
      }
      
      // toggle (hide/show) marker list of a given type
      function toggleList(type) {
        $("#list .list-"+type).toggle();
      }


      // hover on list item
      function markerListMouseOver(marker_id) {
        $("#marker"+marker_id).css("display", "inline");
      }
      function markerListMouseOut(marker_id) {
        $("#marker"+marker_id).css("display", "none");
      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    
    <? echo $head_html; ?>
  </head>
  <body>
    
    <!-- display error overlay if something went wrong -->
    <?php echo $error; ?>
    
    <!-- facebook like button code -->
	<div id="fb-root"></div>
	<script>(function(d, s, id) {
 	 	var js, fjs = d.getElementsByTagName(s)[0];
	  	if (d.getElementById(id)) return;
  		js = d.createElement(s); js.id = id;
  		js.src = "//connect.facebook.net/es_LA/all.js#xfbml=1";
  		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));</script>
    
    <!-- google map -->
    <div id="map_canvas"></div>
    
    <!-- topbar -->
    <div class="topbar" id="topbar">
      <div class="wrapper">
        <div class="left">
          <div class="logo">
            <a href="./">
            <img src="images/logo.png" alt="" />
            </a>
          </div>
          <div class="buttons">
            <a href="#modal_info" class="btn btn-large btn-info" data-toggle="modal"><i class="icon-info-sign icon-white"></i>Sobre este mapa</a>
          </div>
          <div class="buttons">
				<?php
  				$query = "SELECT COUNT(*) AS contador FROM `places` WHERE approved='1' AND start_date <= DATE('$today') AND end_date >= DATE('$today')" ;
   			$today_count = mysql_query("$query");
   			$marker = mysql_fetch_assoc($today_count);   
   			?>
            <a href="index.php?periodo=hoy" class="btn btn-large btn-success"><i class="icon-info-sign icon-white"></i>Hoy (<?php echo $marker[contador]; ?>)</a>
          </div>
          <div class="buttons">
				<?php
  				$query = "SELECT COUNT(*) AS contador FROM places WHERE approved='1' AND start_date <= DATE('$manana') AND end_date >= DATE('$manana')" ;
   			$today_count = mysql_query("$query");
   			$marker = mysql_fetch_assoc($today_count);   
   			?>
            <a href="index.php?periodo=manana" class="btn btn-large btn-success"><i class="icon-info-sign icon-white"></i>Mañana (<?php echo $marker[contador]; ?>)</a>
          </div>
          <div class="buttons">
				<?php
  				$query = "SELECT COUNT(*) AS contador FROM places WHERE approved='1' AND start_date <= DATE('$semana') AND end_date >= DATE('$today')" ;
   			$today_count = mysql_query("$query");
   			$marker = mysql_fetch_assoc($today_count);   
   			?>
            <a href="index.php?periodo=semana" class="btn btn-large btn-success"><i class="icon-info-sign icon-white"></i>Durante una semana (<?php echo $marker[contador]; ?>)</a>
          </div>
          
          
 
        </div>
        <div class="right">
        <?php if( $autentificado == "SI") { ?>
        <div class="admin-buttons">
        		<a href="#modal_add" class="btn btn-large btn-success" data-toggle="modal"><i class="icon-plus-sign icon-white"></i>Añade una protesta</a>
 				<a href="./admin/admin.php" class="btn btn-large btn-admin"><i class="icon-user icon-white"></i>Administración</a>
        		<a href="index.php?task=logout" class="btn btn-large btn-salir"><i class="icon-off icon-white"></i>Salir</a>
        </div>
          <?php } ?>
          <div class="share">
            <a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.manifiestate.net" data-text="Pongamos todas las huelgas y manifestaciones en el mapa:" data-via="dandolamurga_" data-count="yes">Tweet</a>
            <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
            <div class="fb-like" data-href="http://www.manifiestate.net" data-send="false" data-layout="button_count" data-width="450" data-show-faces="true" data-font="tahoma"></div>
         </div>
        </div>
      </div>
    </div>
    
    <!-- right-side gutter -->
    <div class="menu" id="menu">
      <ul class="list" id="list">
      	<li class='category'>
         	<div class='category_item'>
         	<h3 align="center">PROTESTAS PROGRAMADAS</h3>
            </div>
         </li>
        <?php
          $marker_id = 0;
          foreach($places_types as $type) {
          	switch($periodo) {
					case hoy :
						$markers = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND start_date <= DATE('$today') AND end_date >= DATE('$today') ORDER BY title");
						break;
					case manana :
						$markers = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND start_date <= DATE('$manana') AND end_date >= DATE('$manana') ORDER BY title");
						break;
					case semana :
						$markers = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND start_date <= DATE('$semana') AND end_date >= DATE('$today') ORDER BY title");
						break;
					default :
						$markers = mysql_query("SELECT * FROM places WHERE approved='1' AND type='$type[0]' AND end_date >= DATE('$today') ORDER BY title");
						
					}
         	$markers_total = mysql_num_rows($markers);
            echo "
              <li class='category'>
                <div class='category_item'>
                  <div class='category_toggle' onClick=\"toggle('$type[0]')\" id='filter_$type[0]'></div>
                  <a href='#' onClick=\"toggleList('$type[0]');\" class='category_info'><img src='./images/icons/$type[0].png' alt='' />$type[1]<span class='total'> ($markers_total)</span></a>
                </div>
                <ul class='list-items list-$type[0]'>
            ";
            while($marker = mysql_fetch_assoc($markers)) {
              echo "
                  <li class='".$marker[type]."'>
                    <a href='#' onMouseOver=\"markerListMouseOver('".$marker_id."')\" onMouseOut=\"markerListMouseOut('".$marker_id."')\" onClick=\"goToMarker('".$marker_id."');\">".$marker[title]."</a>
                  </li>
              ";
              $marker_id++;
            }
            echo "
                </ul>
              </li>
            ";
          }
        ?>
        <li class='category'>
          <div class=" search">
				<a href='#' class='category_info'>
            <input type="text" name="search" id="search" placeholder="Busca una protesta..." data-provide="typeahead" autocomplete="off" />
				</a>          
          </div>
		  </li>
        <li class="blurb">
        Este mapa ha sido creado por <a href="http://www.dandolamurga.es" target="_blank">Dandolamurga</a> para que se conozcan todas las protestas que se están llevando a cabo en España en estos momentos.
		  Pongamos las protestas en conocimiento!
        </li>
        <li class="attribution">
          <!-- per our license, you may not remove this line -->
          <?=$attribution?>
        </li>
      </ul>
    </div>
    
    <!-- more info modal -->
    <div class="modal hide" id="modal_info">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h3>Acerca Manifiestate.net</h3>
      </div>
      <div class="modal-body">
        <p>Manifiestate.net se ha creado con el objetivo de poner en conocimiento todas las protestas que se están llevando a cabo en España.</p>
		  <p>A menudo nos ocurre que solamente conocemos las protestas más representativas del país, aquéllas a las que los medios de comunicación dan voz. No obstante, existen un gran número de protestas que desconocemos y que dichos colectivos necesitan que se sepa por lo qu están luchando.</p>
		  <p>Con ayuda de los sindicatos y asociaciones estamos formando un mapa con el que mantener actualizadas aquellas protestas que se están llevando a cabo o bien están programadas. De esta forma todo el mundo podrá saber qué protestas hay cerca suya y se le podrá dar más difusión a través de las redes sociales permitiéndonos organizarnos de mejor manera y conocer la magnitud de los movimientos en el país.</p>
        <p>Pongamos todas las protestas en el mapa!!</p>
        <p>¿Preguntas? ¿Sugerencias? ¿Eres un sindicato/asociación y quieres colaborar? Contacta con: <a href="http://www.twitter.com/dandolamurga_" target="_blank">@dandolamurga_</a> o en <a>dandolamurgablog@gmail.com</a></p>
        <p><a href="http://www.dandolamurga.es" target="_blank">www.dandolamurga.es</a></p>
      </div>
      <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal" style="float: right;">Cerrar</a>
      </div>
    </div>
  
  
    
    <!-- add something modal -->
   
    <div class="modal hide" id="modal_add">
 
      <form action="add.php" id="modal_addform" class="form-horizontal">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h3>Introduce una protesta!</h3>
        </div>
        <div class="modal-body">
          <div id="result"></div>
          <fieldset>
            <div class="control-group">
              <label class="control-label" for="add_title">Nombre Protesta</label>
              <div class="controls">
                <input type="text" class="input-xlarge" name="title" id="add_title" maxlength="100" autocomplete="off">
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="input01">Tipo de protesta</label>
              <div class="controls">
                <select name="type" id="add_type" class="input-xlarge">
                	<?php
                	foreach($places_types as $type)
					{
						echo "<option value=\"".$type[0]."\">".$type[1]."</option>";
					}
					?>
                </select>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_address">Ubicación</label>
              <div class="controls">
                <input type="text" class="input-xlarge" name="address" id="add_address">
                <p class="help-block">
                  Suele ser la <b>calle completa (incluyendo ciudad y CP)</b> de la convocatoria.
                  Si funciona en Google Maps, funcionará aquí.
                </p>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_description">Descripción</label>
              <div class="controls">
                <textarea class="input input-xlarge" id="add_description" maxlength="<?php echo $place_desc_maxlength; ?>" name="description"></textarea>
                <p class="help-block">
                  Breve y concisa descripción. ¿Qué se reivindica y por qué? ¿Qué está ocurriendo? Max <?php echo $place_desc_maxlength; ?> carac.
                </p>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_start_date">Fecha Inicio</label>
              <div class="controls">
                <input type="text" class="input-xlarge" name="start_date" id="add_start_date" placeholder="YYYY-MM-DD">
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_end_date">Fecha Fin</label>
              <div class="controls">
                <input type="text" class="input-xlarge" name="end_date" id="add_end_date" placeholder="YYYY-MM-DD">
                <p class="help-block">
                  Fecha en formato YYYY-MM-DD. Ej: 2013-08-21
                </p>
              </div>
            </div>         
            <div class="control-group">
              <label class="control-label" for="add_uri">URL del sitio</label>
              <div class="controls">
                <input type="text" class="input-xlarge" id="add_uri" name="uri" placeholder="http://">
                <p class="help-block">
                  Página web, grupo de Facebook,...
                </p>
              </div>
            </div>
            <div class="control-group">
              <label class="control-label" for="add_uri">Hashtag en Twitter</label>
              <div class="controls">
                <input type="text" class="input-xlarge" id="add_hashtag" name="hashtag" placeholder="#">
                <p class="help-block">
                  Etiqueta en Twitter. Ej: #15M
                </p>
              </div>
            </div>
          </fieldset>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary" id="btn-submit">Añadir para su revisión</button>
          <button class="btn btn-success" id="btn-refresh" >Añadir otra protesta</button>
          <a href="#" class="btn" data-dismiss="modal" style="float: right;">Cerrar</a>
        </div>
      </form>

    </div>
    
    
    
    
    
    <script>
      $(document).ready(function(){
        $("#modal_addform #btn-refresh").css("display", "none");
        $("#modal_addform #btn-refresh").css("float", "left");
        $("#modal_addform #btn-refresh").click( function (){
        	window.location.href="index.php?task=modal_add";
        });
        $("#modal_addform #btn-submit").click( function (){
        	$("#modal_addform #btn-submit").attr("disabled", true);
        });
              
        
      });
    
    
      // add modal form submit
      $("#modal_addform").submit(function(event) {
        event.preventDefault(); 
        // get values
        var $form = $( this ),
            title = $form.find( '#add_title' ).val(),
            type = $form.find( '#add_type' ).val(),
            address = $form.find( '#add_address' ).val(),
            start_date = $form.find( '#add_start_date' ).val(),
            end_date = $form.find( '#add_end_date' ).val(),
            uri = $form.find( '#add_uri' ).val(),
            description = $form.find( '#add_description' ).val(),
            hashtag = $form.find( '#add_hashtag' ).val(),
            url = $form.attr( 'action' );

        // send data and get results
        $.post( url, {title: title, type: type, start_date : start_date, end_date : end_date, address: address, uri: uri, description: description, hashtag: hashtag },
          function( data ) {
            var content = $( data ).find( '#content' );
            
            // if submission was successful, show info alert
            if(data == "success") {
              $("#modal_addform #result").html("Hemos recibido su protesta y en breve será revisada. Gracias!"); 
              $("#modal_addform #result").addClass("alert alert-info");
              $("#modal_addform p").css("display", "none");
              $("#modal_addform fieldset").css("display", "none");
              $("#modal_addform #btn-submit").css("display", "none");
 			  $("#modal_addform #btn-refresh").css("display", "block");
 
            // if submission failed, show error
            } else {
              $("#modal_addform #result").html(data); 
              $("#modal_addform #result").addClass("alert alert-danger");
              $("#modal_addform #btn-submit").attr("disabled", false);
              $("#modal_addform .modal-body").stop().scrollTop(0); 
            }
          }
        );
      });
    </script>    
  </body>
</html>
